package edu.uoc.tdp.pac4.client.conexion;
import edu.uoc.tdp.pac4.EAssistencia;
import edu.uoc.tdp.pac4.beans.Usuario;
import edu.uoc.tdp.pac4.client.PnlMain;
import edu.uoc.tdp.pac4.remote.Conexion;
import edu.uoc.tdp.pac4.util.LanguageUtils;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author eSupport Netbeans
 */
public class PnlLogin extends javax.swing.JDialog {

    private PnlMain parent;
    private Conexion manager;
    private LanguageUtils language;
    private Usuario usuario;

    /**
     * Creates new form PnlLogin
     */
    public PnlLogin(PnlMain parent, boolean modal, Conexion manager, LanguageUtils language) {
        super(parent, modal);        
        this.parent = parent;
        this.manager = manager;
        this.language = language; 
        initComponents();

        this.setLocationRelativeTo(null);                     
    }
    
    /**
     * Devuelve el usuario actual o null si no ha tenido éxito el Login.
     */
    public Usuario getCurrentUser()
    {
       return this.usuario;
    }
    
   /**
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblUsuario = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        cmbAceptar = new javax.swing.JButton();
        cmbCancelar = new javax.swing.JButton();
        txtPassword = new javax.swing.JPasswordField();
        lblIcono = new javax.swing.JLabel();
        lblValida = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(language.getProperty("cnxmatricula.pnllogin.title"));
        setModal(true);
        setName("jFrmLogin"); // NOI18N
        setResizable(false);

        lblUsuario.setText(language.getProperty("cnxmatricula.pnllogin.usuario"));

        lblPassword.setText(language.getProperty("cnxmatricula.pnllogin.pass"));

        cmbAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/tick-button.png"))); // NOI18N
        cmbAceptar.setText(language.getProperty("cnxmatricula.pnllogin.aceptar"));
        cmbAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbAceptarActionPerformed(evt);
            }
        });

        cmbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/object_delete.gif"))); // NOI18N
        cmbCancelar.setText(language.getProperty("cnxmatricula.pnllogin.cancelar"));
        cmbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbCancelarActionPerformed(evt);
            }
        });

        lblIcono.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/user-lock-icon.png"))); // NOI18N

        lblValida.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/lightning.png"))); // NOI18N
        lblValida.setText(language.getProperty("cnxmatricula.pnllogin.perfiles"));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtPassword)
                    .addComponent(txtUsuario)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lblValida)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblIcono))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblUsuario)
                            .addComponent(lblPassword)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmbAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbCancelar)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblIcono)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(lblValida)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addComponent(lblUsuario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblPassword)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbAceptar)
                    .addComponent(cmbCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cmbAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbAceptarActionPerformed
        
        // Habilita las opciones que requieren conexión
        //TO-DO: Habilitar opciones en función del rol
        try {
            usuario = new Usuario();            
            usuario = manager.validaUsuario(txtUsuario.getText(), new String(txtPassword.getPassword()));            
            if(usuario.getLogin().isEmpty())
            {
                JOptionPane.showMessageDialog       
        	(null, language.getProperty("cnxmatricula.pnllogin.noautorizado"), language.getProperty(EAssistencia.APP_TITLE), JOptionPane.ERROR_MESSAGE);
            }
            else
            {
                JOptionPane.showMessageDialog       
        	(null, language.getProperty("cnxmatricula.pnllogin.autorizado") + usuario.getNombre() + "!", language.getProperty(EAssistencia.APP_TITLE), JOptionPane.INFORMATION_MESSAGE);
                //Pendiente controlar los menús según los roles
                parent.setRolMenuOpciones(usuario.getLogin(), usuario.getIdRol(), usuario.getDescRol());
                this.dispose();
            }
        }catch (SQLException ex) {
            
            JOptionPane.showMessageDialog(null, 
                language.getProperty("err.sql") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                language.getProperty("app.title"), 
                JOptionPane.ERROR_MESSAGE);
            
        }catch (Exception ex) {
            
            JOptionPane.showMessageDialog(null, 
                language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                language.getProperty("app.title"), 
                JOptionPane.ERROR_MESSAGE);
            
        }
        
    }//GEN-LAST:event_cmbAceptarActionPerformed

    private void cmbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_cmbCancelarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmbAceptar;
    private javax.swing.JButton cmbCancelar;
    private javax.swing.JLabel lblIcono;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JLabel lblValida;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
